import React, { Component } from 'react'
import store from '../../redux/store'
import { createIncreatementAction, createDecreatementAction, createIncreatmentAsyncAction } from '../../redux/countAction' 

export default class Count extends Component {
    state = {
        numInput: ''
    }

    // 因为store在改变状态的时候只关注状态，并不会引起页面重新渲染。所以可以使用this.setState进行重新渲染
    // componentDidMount(){
    //     // store.subscribe会在store状态更新时触发
    //     store.subscribe( () => {
    //         this.setState({});
    //     } )
    // }

    // 处理输入的函数
    numInput = ( event ) => {
        this.setState({ numInput: event.target.value });
    }

    // 处理加法的函数
    increatment = () => {
        let numInput = this.state.numInput
        store.dispatch( createIncreatementAction(numInput) )
    }


    // 处理减法的函数
    decreatment = () => {
        let numInput = this.state.numInput
        store.dispatch( createDecreatementAction(numInput) )
    }

    increatmentIfOdd = () => {
        let numInput = this.state.numInput
        if(parseInt(store.getState()) % 2 === 0) {
            return;
        }
        store.dispatch( createIncreatementAction(numInput) )
    }


    increatmentAsync = () => {
        let numInput = this.state.numInput
        store.dispatch( createIncreatmentAsyncAction( numInput, 500 ) )
        
    }

    render() {
        return (
            <div>
                <h1>当前值为{ store.getState() }</h1>
                <input type="text" onChange={ this.numInput }/>
                <button onClick={ this.increatment }>+</button>
                <button onClick={ this.decreatment }>-</button>
                <button onClick={ this.increatmentIfOdd }>increatmentIfOdd</button>
                <button onClick={ this.increatmentAsync }>increatmentAsync</button>
            </div>
        )
    }
}
